package cn.ording.util;


public class Page {

	public static final int DEFAULT_PAGE_SIZE = 10;

	private int pageIndex;
	private int pageSize;
	private int totalCount;
	private int pageCount;
	private int preIndex;
	private int nextIndex;
	private String conditions;

	public Page(int pageIndex, int pageSize) {
		// check:
		if (pageIndex < 1)
			pageIndex = 1;
		if (pageSize < 1)
			pageSize = 1;
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;
	}

	public Page(){
	}
	
	public Page(int pageIndex) {
		this(pageIndex, DEFAULT_PAGE_SIZE);
	}

	public int getPageIndex() {
		return pageIndex;
	}

	public int getPageSize() {
		return pageSize;
	}

	public int getPageCount() {
		return pageCount;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public int getFirstResult() {
		return (pageIndex - 1) * pageSize;
	}

	public boolean getHasPrevious() {
		return pageIndex > 1;
	}

	public boolean getHasNext() {
		return pageIndex < pageCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
		pageCount = totalCount / pageSize + (totalCount % pageSize == 0 ? 0 : 1);
		// adjust pageIndex:
		if (totalCount == 0) {
			if (pageIndex != 1)
				throw new IndexOutOfBoundsException("Page index out of range.");
		} else {
			if (pageIndex > pageCount)
				throw new IndexOutOfBoundsException("Page index out of range.");
		}
	}

	public boolean isEmpty() {
		return totalCount == 0;
	}

	public String getConditions() {
		return conditions;
	}

	public void setConditions(String conditions) {
		this.conditions = conditions;
	}

	public int getPreIndex() {
		return (getHasPrevious()?pageIndex-1:pageIndex);
	}

	public void setPreIndex(int preIndex) {
		this.preIndex = preIndex;
	}

	public int getNextIndex() {
		return (getHasNext()?pageIndex+1:pageIndex);
	}

	public void setNextIndex(int nextIndex) {
		this.nextIndex = nextIndex;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

}

